package com.cskaoyan.service;

import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.domain.*;
import com.cskaoyan.mapper.MarketCartMapper;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import com.cskaoyan.mapper.MarketSystemMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CouponServiceImpl implements CouponService {
@Autowired
    MarketCouponMapper couponMapper;
@Autowired
    MarketCouponUserMapper couponUserMapper;
@Autowired
MarketCartMapper cartMapper;
@Autowired
MarketSystemMapper systemMapper;
    @Override
    public BaseRespVo getList(Integer page, Integer limit) {
        MarketCouponExample couponExample = new MarketCouponExample();
        couponExample.createCriteria().andDeletedEqualTo(false).andStatusEqualTo((short) 0);
        List<MarketCoupon> coupons = couponMapper.selectByExampleSelective(couponExample);
        List<Map<String,Object>> list=new ArrayList<>();
        if (coupons.size() != 0) {
            for (MarketCoupon coupon : coupons) {
                Map<String,Object> map=new HashMap<>();
                map.put("id",coupon.getId());
                map.put("name",coupon.getName());
                map.put("desc",coupon.getDesc());
                map.put("discount",coupon.getDiscount());
                map.put("min",coupon.getMin());
                map.put("days",coupon.getDays());
                map.put("tag",coupon.getTag());
                list.add(map);
            }
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
        CommonData data = CommonData.data(pageInfo);
        return BaseRespVo.ok(data);

    }

    @Override
    public BaseRespVo getMylist(Integer page, Integer limit, Integer status, Integer userId) {
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false)
                                .andStatusEqualTo(Short.parseShort(status.toString()))
                .andEndTimeGreaterThan(LocalDateTime.now());
        PageHelper.startPage(page,limit);
        List<MarketCouponUser> couponUserList = couponUserMapper.selectByExampleSelective(couponUserExample);
        List<Map> list=new ArrayList<>();
        if (couponUserList.size() != 0) {
            for (MarketCouponUser couponUser : couponUserList) {
             Map<String,Object> map=new HashMap<>();
                Integer couponId = couponUser.getCouponId();
                MarketCoupon coupon = couponMapper.selectByPrimaryKey(couponId);
                map.put("id",couponUser.getId());
                map.put("cid",couponId);
                map.put("name",coupon.getName());
                map.put("desc",coupon.getDesc());
                map.put("discount",coupon.getDiscount());
                map.put("endTime",couponUser.getEndTime());
                map.put("startTime",couponUser.getStartTime());
                map.put("min",coupon.getMin());
                map.put("tag",coupon.getTag());
                if (couponUser.getEndTime().isAfter(LocalDateTime.now())
                        && coupon.getStatus() == 0
                        &&couponUser.getStartTime().isAfter(LocalDateTime.now())) {
                    map.put("available", true);
                } else {
                    map.put("available", false);
                }
                list.add(map);
            }
        }
        PageInfo<Map> pageInfo = new PageInfo<>(list);
        CommonData data = CommonData.data(pageInfo);
        return BaseRespVo.ok(data);
    }

    @Override
    public BaseRespVo selectCoupon(Integer cartId, Integer grouponRulesId, Integer userId) {
        List<MarketCart> checkedGoodsList=null;
        BaseRespVo brv = this.getMylist(1, 10, 0, userId);
        CommonData commonData = (CommonData) brv.getData();
        List<Map> list = commonData.getList();
        BigDecimal actualPrice = BigDecimal.ZERO;
        //商品合计
        BigDecimal totalPrice = BigDecimal.ZERO;
        //运费金额
        BigDecimal freightPrice = BigDecimal.ZERO;
        //优惠劵金额
        BigDecimal couponPrice = BigDecimal.ZERO;
//        if (cartId == 0) {
            MarketCartExample cartExample = new MarketCartExample();
            cartExample.createCriteria().andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
            checkedGoodsList = cartMapper.selectByExampleSelective(cartExample);
            //根据checked=1算总金额，金额超过运费满减，则不添加运费；不够满减标准，则添加运费，如果有优惠券，减去优惠券金额
            //实付金额

            for (MarketCart marketCart : checkedGoodsList) {
                BigDecimal singlePrice = marketCart.getPrice();
                Short number = marketCart.getNumber();
                totalPrice = totalPrice.add(singlePrice.multiply(new BigDecimal(number.toString())));
            }
            //从system表中找freight-value和freight-min，即运费金额和满减金额
            String freightMin = systemMapper.selectKeyNameAndKeyValue("market_express_freight_min");
            String freightValue = systemMapper.selectKeyNameAndKeyValue("market_express_freight_value");
            //如果商品金额小于满减金额，则不减运费
            if (totalPrice.compareTo(new BigDecimal(freightMin)) == -1) {
                freightPrice = new BigDecimal(freightValue);
            } else {
                freightPrice = BigDecimal.ZERO;
            }
            BigDecimal orderTotalPrice = totalPrice.add(freightPrice);

            for (Map map : list) {
                BigDecimal min = (BigDecimal) map.get("min");
                //商品价格大于等于min可以使用
                if (orderTotalPrice.compareTo(min) > -1) {
                    map.put("available", true);
                } else {
                    map.put("available", false);
                }
            }
       // }
        /*else {
            MarketCart cart = cartMapper.selectByPrimaryKey(cartId);
            BigDecimal singlePrice = cart.getPrice();
            Short number = cart.getNumber();
            totalPrice = totalPrice.add(singlePrice.multiply(new BigDecimal(number.toString())));
            String freightMin = systemMapper.selectKeyNameAndKeyValue("market_express_freight_min");
            String freightValue = systemMapper.selectKeyNameAndKeyValue("market_express_freight_value");
            //如果商品金额小于满减金额，则不减运费
            if (totalPrice.compareTo(new BigDecimal(freightMin)) == -1) {
                freightPrice = new BigDecimal(freightValue);
            } else {
                freightPrice = BigDecimal.ZERO;
            }
            BigDecimal orderTotalPrice = totalPrice.add(freightPrice);
           list = (List<Map>) brv.getData();
            for (Map map : list) {
                BigDecimal min = (BigDecimal) map.get("min");
                //商品价格大于等于min可以使用
                if (orderTotalPrice.compareTo(min) > -1) {
                    map.put("available", true);
                } else {
                    map.put("available", false);
                }
            }
        }*/
        PageInfo<Map> pageInfo = new PageInfo<>(list);
        CommonData data = CommonData.data(pageInfo);
        return BaseRespVo.ok(data);

    }

    @Override
    @Transactional
    public BaseRespVo receiveCoupon(Map map, Integer userId) {
        Integer couponId = (Integer) map.get("couponId");
        MarketCoupon coupon = couponMapper.selectByPrimaryKey(couponId);
        MarketCouponUserExample userExample = new MarketCouponUserExample();
       userExample .createCriteria().andUserIdEqualTo(userId)
                .andCouponIdEqualTo(couponId).andDeletedEqualTo(false);
        List<MarketCouponUser> couponUsers = couponUserMapper.selectByExampleSelective(userExample);
        Integer total = coupon.getTotal();
        if (total > 0) {
            coupon.setTotal(total - 1);
            couponMapper.updateByPrimaryKey(coupon);
            if (couponUsers.size() == 0) {
                MarketCouponUser couponUser = new MarketCouponUser();
                couponUser.setUserId(userId);
                couponUser.setDeleted(false);
                couponUser.setStatus((short) 0);
                couponUser.setAddTime(LocalDateTime.now());
                couponUser.setUpdateTime(LocalDateTime.now());
                couponUser.setStartTime(LocalDateTime.now());
                Short days = coupon.getDays();
                couponUser.setEndTime(LocalDateTime.now().plusDays(days));
                couponUser.setCouponId(couponId);
                couponUserMapper.insertSelective(couponUser);
            } else {
                return BaseRespVo.fail("优惠券已领取过！");
            }
        } else {
            return BaseRespVo.fail("优惠券已领完！");
        }
        return BaseRespVo.ok();
    }

    @Override
    @Transactional
    public BaseRespVo exchangeCoupon(Map map, Integer userId) {
        String code = (String) map.get("code");
        MarketCouponExample couponExample = new MarketCouponExample();
        couponExample.createCriteria().andTypeEqualTo((short) 2).andDeletedEqualTo(false).andCodeEqualTo(code);
        List<MarketCoupon> couponList = couponMapper.selectByExampleSelective(couponExample);
        if (couponList.size() == 0) {
            return BaseRespVo.fail("优惠券不正确！");
        } else {
            MarketCoupon coupon = couponList.get(0);
            Integer couponId = coupon.getId();
            Map<String,Integer> couponIdMap=new HashMap<>();
            couponIdMap.put("couponId",couponId);
           return this.receiveCoupon(couponIdMap,userId);
        }
    }
}
